package cn.weiyan.dtx.tccdemo.bank2.server.impl;

import cn.weiyan.dtx.tccdemo.bank2.dao.AccountInfoDao;
import cn.weiyan.dtx.tccdemo.bank2.server.AccountInfoServer;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hmily.annotation.Hmily;
import org.dromara.hmily.core.concurrent.threadlocal.HmilyTransactionContextLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author misterWei
 * @create 2020年02月14号:17点41分
 * @mailbox mynameisweiyan@gmail.com
 */
@Service
@Slf4j
@SuppressWarnings("all")
public class AccountInfoServerImpl implements AccountInfoServer {

    @Autowired
    private AccountInfoDao accountInfoDao;



    // 该Hmily 方法标注在那个方法上的时候就说明该方法是一个try方法,然后置顶 confirm || cancel 方法
    @Hmily(confirmMethod = "commitMethod",cancelMethod = "rollbackMethod")
    @Override
    public void updateAccountBalance(String accountNo, Double amount) {
        String transId = HmilyTransactionContextLocal.getInstance().get().getTransId();
        log.info(" Bank2 Service 已经执行try 方法，事务id:{} "+transId );

    }

    @Transactional
    public void commitMethod(String accountNo, Double amount){
        String transId = HmilyTransactionContextLocal.getInstance().get().getTransId();


        //进行幂等性校验
        if (accountInfoDao.isExistConfirm(transId) > 0 ){
            log.info(" Bank2 Service 已经执行过 confirm 方法了 不必执行，事务id:{} "+transId );
        }
        // 进行业务操纵
        accountInfoDao.addAccountBalance(accountNo,amount);
       //增加幂等性校验凭证
        accountInfoDao.addConfirm(transId);


    }

    @Transactional
    public void rollbackMethod(String accountNo, Double amount){
        String transId = HmilyTransactionContextLocal.getInstance().get().getTransId();
        log.info(" Bank2 Service 已经执行cancel 方法，事务id:{} "+transId );
    }
}
